/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.repository;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import org.gtugs.domain.Chapter;
import org.springframework.orm.jdo.support.JdoDaoSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class JdoChapterDao extends JdoDaoSupport implements ChapterDao {

  public JdoChapterDao() {
    super();
    setPersistenceManagerFactory(PMF.get());
  }

  public Integer getChapterCount() {
    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery(Chapter.class);
    query.setResult("count(this)");
    int count = 0;

    try {
      count = (Integer) query.execute();
    } finally {
      pm.close();
    }

    return count;
  }

  public Chapter getChapter(Long id) {
    PersistenceManager pm = getPersistenceManager();
    Chapter chapter = null;

    try {
      chapter = pm.getObjectById(Chapter.class, id);

      // Lazily load administrator list
      chapter.getAdministrators();

      // Detach chapter
      chapter = pm.detachCopy(chapter);
    } catch (JDOObjectNotFoundException e) {
      return null;
    } finally {
      pm.close();
    }

    return chapter;
  }

  @SuppressWarnings("unchecked")
  public List<Chapter> getChapters() {
    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery(Chapter.class);

    try {
      List<Chapter> results = (List<Chapter>) query.execute();

      if (results != null && results.size() > 0) {
        return (List<Chapter>) pm.detachCopyAll(results);
      }
    } finally {
      query.closeAll();
    }

    return null;
  }

  @SuppressWarnings("unchecked")
  public List<Chapter> getActiveChapters() {
    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery(Chapter.class);
    query.setFilter("status != 'inactive'");

    try {
      List<Chapter> results = (List<Chapter>) query.execute();

      if (results != null && results.size() > 0) {
        return (List<Chapter>) pm.detachCopyAll(results);
      }
    } finally {
      query.closeAll();
    }

    return null;
  }

  public List<Chapter> getChapters(Set<Long> ids) {
    List<Key> keys = new ArrayList<Key>(ids.size());
    for (Long id : ids) {
      keys.add(KeyFactory.createKey(Chapter.class.getSimpleName(), id));
    }

    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery("select from " + Chapter.class.getName() +
        " where key == :keys");

    try {
      List<Chapter> results = (List<Chapter>) query.execute(keys);

      if (results != null && results.size() > 0) {
        return (List<Chapter>) pm.detachCopyAll(results);
      }
    } finally {
      query.closeAll();
      pm.close();
    }

    return null;
  }

  @SuppressWarnings("unchecked")
  public List<Chapter> getChaptersOrderedByCountry() {
    PersistenceManager pm = getPersistenceManager();
    Query query = pm.newQuery(Chapter.class);
    query.setOrdering("country asc, name asc");

    try {
      List<Chapter> results = (List<Chapter>) query.execute();

      if (results != null && results.size() > 0) {
        return (List<Chapter>) pm.detachCopyAll(results);
      }
    } finally {
      query.closeAll();
    }

    return null;
  }

  public void storeChapter(Chapter chapter) {
    getJdoTemplate().makePersistent(chapter);
  }
}
